package net.zhangdaqian.lightDom;

import java.io.Serializable;

public class LightUrl  implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = -4042339997016320829L;
	private String url;
	private Integer[] stackKeep;
	private String protocol;
	private String host;

	public String getProtocol() {
		return protocol;
	}

	public String getURI() {
		return url;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public String getHost() {
		return host;
	}

	public void setURI(String uri) {
		if (null != uri) {
			uri = uri.trim();
			if (uri.length() - 1 > 0 && uri.charAt(uri.length() - 1) == '/') {
			} else {
				this.protocol = uri.substring(0, uri.indexOf("://"));
				StringBuffer host = new StringBuffer();
				{
					int i = protocol.length() + 3;

					for (; i < uri.length() && uri.charAt(i) != '/'; i++) {
						host.append(uri.charAt(i));
					}
					this.setHost(host.toString());

					if (i == uri.length()) {
						uri = uri + '/';
						this.url = uri;
					}
				}
				Boolean haveDotMarket = false;
				if (uri.charAt(uri.length() - 1) != '/') {
					for (int j = uri.length() - 1; j >= 3
							&& haveDotMarket == false; j--) {
						if (uri.charAt(j) == '.') {
							haveDotMarket = true;
						} else if (uri.charAt(j) == '/') {
							uri = uri + '/';
							break;
						}
					}
				}

			}
			// url = uri;
			int count = 0;
			for (int i = 0; i < uri.length(); i++) {
				if (uri.charAt(i) == '/') {
					count++;
				}
			}
			stackKeep = new Integer[count];
			for (int i = 0, j = 0; i < uri.length(); i++) {
				if (uri.charAt(i) == '/') {
					stackKeep[j] = i;
					j++;
				}
			}

			this.url = uri;
		} else {
			setURI("http://localhost.error/");
		}
	}

	public LightUrl() {
	}

	public LightUrl(String parentURI) {
		setURI(parentURI);
	}

	public String merge(String adduri) {
		String result = "";
		if (adduri.indexOf("://") >= 0) {
			result = adduri;
		} else {
			adduri = adduri.trim();
			int i = 0;
			if (adduri.charAt(0) == '/') {
				result = url.substring(0, url.indexOf('/',
						url.indexOf("://") + 3) + 1)
						+ adduri.substring(1);
			} else {
				int fatherLayer = 0;
				int currentLayer = 0;
				while (i < adduri.length()
						&& (adduri.charAt(i) == '.' || adduri.charAt(i) == '/')) {
					if (i + 3 < adduri.length() && adduri.charAt(i) == '.'
							&& adduri.charAt(i + 1) == '.'
							&& adduri.charAt(i + 2) == '/') {
						i = i + 3;
						fatherLayer++;
					} else if (i + 2 < adduri.length()
							&& adduri.charAt(i) == '.'
							&& adduri.charAt(i + 1) == '/') {
						i = i + 2;
						currentLayer++;
					} else {
						break;
					}
				}
				result = url.substring(0, stackKeep[stackKeep.length - 1
						- fatherLayer] + 1)
						+ adduri.substring(i);
			}
		}
		return result;
	}

}
